package com.tao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.config.MyLog;
import com.tao.pojo.Menu;
import com.tao.pojo.vo.ResponseResult;
import com.tao.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class CmsMenuController {
    @Autowired
    private MenuService menuService;

    @MyLog("菜单列表")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/list")
    public Object list(@RequestBody Menu menu){
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
        lqw.like(!ObjectUtils.isEmpty(menu.getMenuName()),Menu::getMenuName,menu.getMenuName());
        List<Menu> list = menuService.list(lqw);
        return ResponseResult.success(list);
    }

    @MyLog("菜单新增")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/add")
    public Object add(@RequestBody Menu menu){
        if (ObjectUtils.isEmpty(menu.getMenuName())){
            return ResponseResult.error("菜单名称必填！");
        }
        menuService.save(menu);
        return ResponseResult.success(null);
    }

    @MyLog("菜单修改")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/update")
    public Object update(@RequestBody Menu menu){
        if (ObjectUtils.isEmpty(menu.getMenuName())){
            return ResponseResult.error("菜单名称必填！");
        }
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Menu::getMenuName,menu.getMenuName());
        List<Menu> list = menuService.list(lqw);
        if (list.size()<1){
            return ResponseResult.error("菜单不存在！");
        }
        menuService.updateById(menu);
        return ResponseResult.success(null);
    }

    @MyLog("菜单删除")
    @PreAuthorize("hasAnyAuthority('admin')")
    @PostMapping("/remove")
    public Object remove(@RequestBody Menu menu){
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Menu::getMenuName,menu.getMenuName());
        List<Menu> list = menuService.list(lqw);
        if (list.size()<1){
            return ResponseResult.error("菜单不存在！");
        }
        menuService.removeById(menu.getId());
        return ResponseResult.success(null);
    }
}
